package com.yimi.yinhepda.views.main.my_module

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import cn.uce.pda.R
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.pda.uce.commom.observable.CommomObservale
import com.pda.uce.commom.util.*
import com.uce.pda.util.AlertDialogUtils
import com.uce.pda.util.ClsUtils
import com.uce.pda.util.JavaUtils
import com.uce.pda.view.BluetoothLoadingDialog
import com.uce.pda.watcher.SwitchButton
import com.webview.MainHandler
import com.pda.ym.base.BaseActivity
import kotlinx.android.synthetic.main.activity_bluetooth.*
import java.util.*


/**
 * 蓝牙列表集合界面
 */

class BlueToothActivity : BaseActivity(), View.OnClickListener, Observer {
    lateinit var dialog: BluetoothLoadingDialog

    override fun update(p0: Observable?, p1: Any?) {
        val str = (p0 as CommomObservale).t
        if (!TextUtils.isEmpty(str)) {
            isScanConnected = true
            blueToolthMatcher(JavaUtils.splitStr(str))
        }
    }

    //蓝牙配对
    fun blueToolthMatcher(blueToothAddress: String) {
        /**
         *检查蓝牙地址是否是正规的蓝牙地址
         */
        if (BluetoothAdapter.checkBluetoothAddress(blueToothAddress)) {
            //蓝牙配对
            val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
            if (bluetoothAdapter.isEnabled){
                if (JavaUtils.mapMac.get(blueToothAddress)!=null){
                    val bluetoothDevice = bluetoothAdapter.getRemoteDevice(blueToothAddress)
                    JavaUtils.createBond(bluetoothDevice)
                }
                else{
                    ToastUtil.showToast(String.format(getString(R.string.blue_tooth_is_not_foud),blueToothAddress))
                }

            }
            else{
                ToastUtil.showToast(getString(R.string.blue_tooth_is_not_enable))
            }
        } else {
            ToastUtil.showToast(getString(R.string.bluetooth_mac_address_error))
        }
    }


    val list_rec = mutableListOf<BluetoothDevice>()
    val list_data = mutableListOf<String>()
    lateinit var mBluetoothAdapter: BluetoothAdapter

    override fun getPageName(): String? {
        return "蓝牙列表"
    }


    override fun onClick(p0: View) {
        if (p0.id == com.yimi.yinhepda.R.id.relativ_hand_connect) { //手动链接
            isHandleConnect = true
            isScanConnected=false
            startActivity(Intent(Settings.ACTION_BLUETOOTH_SETTINGS))
        } else {
            if (TextUtils.equals(p0.tag as String, Sp_net_Util.getInstance().get("blueTooth"))) {
                return
            }
            reset()
            list_data.clear()
            p0.findViewById<View>(R.id.img_four).visibility = View.VISIBLE
            list_data.add(p0.tag as String)
            Sp_net_Util.getInstance().put("blueTooth", p0.tag as String)
        }
    }

    fun reset() {
        for (i in 0 until list.childCount) {
            list.getChildAt(i).findViewById<View>(R.id.img_four).visibility = View.GONE
        }
    }

    override fun onResume() {
        super.onResume()
        isHandleConnect = false
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(com.yimi.yinhepda.R.layout.activity_bluetooth)
        BaseApplication.commomObservale.addObserver(this)
        JavaUtils.mapMac.clear()
    }

    var isConnected = false //是否连接过
    var isScanConnected = false //是否是扫描连接
    var isHandleConnect = false //是否手动链接
    var pinMa: String = "1234"
    var index = 1 //重试机制2次
    val broad: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(p0: Context, p1: Intent) {
            if (p1.action == BluetoothDevice.ACTION_BOND_STATE_CHANGED) {
                val device: BluetoothDevice = p1.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                val state = p1.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1)
                when (state) {
                    BluetoothDevice.BOND_NONE -> { //解除配对
                        list_rec.remove(device)
                        list_data.remove(device.address)
                        if (Sp_net_Util.getInstance().get("blueTooth") == device.address) {
                            if (list_rec.size > 0) {
                                Sp_net_Util.getInstance().put("blueTooth", list_rec.first().address)
                            } else {
                                Sp_net_Util.getInstance().put("blueTooth", "")
                            }
                        }
                        list.adapter!!.notifyDataSetChanged()
                        retryConnect(p0, p1, device.address)
                    }
                    BluetoothDevice.BOND_BONDED -> { //蓝牙配对成功
                        if (isScanConnected) {
                            dialog!!.dismiss()
                        }
                        list_rec.add(device)
                        if (TextUtils.isEmpty(Sp_net_Util.getInstance().get("blueTooth"))) {
                            list_data.add(device.address)
                            Sp_net_Util.getInstance().put("blueTooth", device.address)
                        }
                        list.adapter?.notifyDataSetChanged()
                    }
                    BluetoothDevice.BOND_BONDING -> {//蓝牙配对中
                        isConnected = true
                        if (isScanConnected) {
                            if (!dialog!!.isShowing) {
                                dialog!!.show()
                            }
                        }
                    }
                }
            } else if (p1.action == "android.bluetooth.device.action.PAIRING_REQUEST") {
                if (isScanConnected) {
                    var mBluetoothDevice = p1.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                    var type = p1.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, BluetoothDevice.ERROR);
                    if (type == BluetoothDevice.PAIRING_VARIANT_PASSKEY_CONFIRMATION) {

                    }
                    try {
                        //(三星)4.3版本测试手机还是会弹出用户交互页面(闪一下)，如果不注释掉下面这句页面不会取消但可以配对成功。(中兴，魅族4(Flyme 6))5.1版本手机两中情况下都正常
                        //                    ClsUtils.setPairingConfirmation(mBluetoothDevice.javaClass, mBluetoothDevice, true);
                        abortBroadcast()//如果没有将广播终止，则会出现一个一闪而过的配对框。
                        //3.调用setPin方法进行配对...
                        ClsUtils.setPin(mBluetoothDevice.javaClass, mBluetoothDevice, pinMa)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }

            } else if (p1.action == BluetoothAdapter.ACTION_STATE_CHANGED) {  //监听蓝牙开关广播
                if (isHandleConnect) {
                    var blueState = p1.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0)
                    when (blueState) {
                        BluetoothAdapter.STATE_ON -> {  //蓝牙打开'
                            switch_btn.isChecked=true
                            getBondedBlueToothDevices()
                            judgeisDiscover()
                        }
                        BluetoothAdapter.STATE_OFF -> {  //蓝牙关闭
                            switch_btn.isChecked=false
                            clearDataList()
                        }

                    }
                }
            }
            else if(BluetoothDevice.ACTION_FOUND==p1.action){ // 蓝牙发现
                // 从intent中获取设备
                val device = p1.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                JavaUtils.mapMac.put(device.address,device.name+"蓝牙名字")
            }
        }

    }

    fun retryConnect(p0: Context, p1: Intent, adder: String) {
        //判断是否通过扫描链接
        if (isScanConnected) {
            //判断是否链接过
            if (isConnected) {
                index++
                if (index > 2) {
                    dialog!!.dismiss()
                    AlertDialogUtils.getInstance().initInputDialog(p0)
                    AlertDialogUtils.getInstance().setCallBackListener(object : AlertDialogUtils.ClickOkCallBackListener {
                        override fun clickOk(address: String?) {
                            pinMa = address!!
                            SpUtil.getInstance().put("pinMa",pinMa)
                            blueToolthMatcher(adder)
                        }
                    })
                } else {
                    var blueToothDevice = p1.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                    if (blueToothDevice != null) {
                        pinMa = "0000"
                        blueToolthMatcher(blueToothDevice.address)
                    }
                }
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(broad)
        BaseApplication.commomObservale.deleteObserver(this)
        JavaUtils.mapMac.clear()
    }

    //判断是否需要扫描
    fun judgeisDiscover(){
       var bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (bluetoothAdapter.isEnabled){
            if (!bluetoothAdapter.isDiscovering()) {  //如果没有在扫描设备
                bluetoothAdapter.startDiscovery();//扫描附近蓝牙设备，然后做接下来的操作，比如扫描附近蓝牙等
            }
        }

    }

    override fun onContentChanged() {
        super.onContentChanged()
        dialog = BluetoothLoadingDialog(BlueToothActivity@ this)
        val filter = IntentFilter()
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
        filter.addAction("android.bluetooth.device.action.PAIRING_REQUEST")
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
        filter.addAction(BluetoothDevice.ACTION_FOUND)
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        registerReceiver(broad, filter)
//
        relativ_hand_connect.setOnClickListener(this)


        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        switch_btn.isChecked=mBluetoothAdapter.isEnabled
        judgeisDiscover()
        switch_btn.setOnCheckedChangeListener(object : SwitchButton.OnCheckedChangeListener {
            override fun onCheckedChanged(buttonView: SwitchButton?, isChecked: Boolean) {
                JavaUtils.mapMac.clear()
                if (!isHandleConnect) {
                    if (!isChecked) {
                        mBluetoothAdapter.disable()
                        clearDataList()
                    } else {
                        judgeisDiscover()
                        mBluetoothAdapter.enable()
                        getBondedBlueToothDevices()
                    }
                }
            }
        })

        list.layoutManager = LinearLayoutManager(this)
        list.addItemDecoration(DividerDecoration("#e5e5e5",
                DisplayUtil.dip2px(1f), 0, 0))
        list.adapter = object : BaseQuickAdapter<BluetoothDevice, BaseViewHolder>(com.yimi.yinhepda.R.layout.item_layout_blue_tooth, list_rec) {
            override fun convert(helper: BaseViewHolder, item: BluetoothDevice, postion: Int) {
                if (TextUtils.equals(item.address, Sp_net_Util.getInstance().get("blueTooth"))){
                    helper.setTextColor(com.yimi.yinhepda.R.id.text_name,ContextCompat.getColor(BaseApplication.application,R.color.blue_tooth_text_color))
                    helper.setTextColor(com.yimi.yinhepda.R.id.text_mac, ContextCompat.getColor(BaseApplication.application,R.color.blue_tooth_text_color))
                }
                else{
                    helper.setTextColor(com.yimi.yinhepda.R.id.text_name,ContextCompat.getColor(BaseApplication.application,R.color.one_ticket_title_text_color))
                    helper.setTextColor(com.yimi.yinhepda.R.id.text_mac, ContextCompat.getColor(BaseApplication.application,R.color.one_ticket_title_text_color))
                }
                if (postion==(list_rec.size-1)){
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        helper.itemView.background=ContextCompat.getDrawable(BaseApplication.application,R.drawable.drawable_one_ticket_item_bottom_white)
                    }
                }
                 if(postion==0&&(list_rec.size==1)){
                     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                         helper.itemView.background=ContextCompat.getDrawable(BaseApplication.application,R.drawable.drawable_shape_home_item_plan)
                     }
                 }
                helper.getView2(com.yimi.yinhepda.R.id.main).tag = item.address
                helper.setText(com.yimi.yinhepda.R.id.text_name, item.name)
                helper.getView2(com.yimi.yinhepda.R.id.main).setOnClickListener(this@BlueToothActivity)
                helper.setText(com.yimi.yinhepda.R.id.text_mac, item.address)
            }
        }
        getBondedBlueToothDevices()

    }


    /***
     * 清除数据
     */
    fun clearDataList() {
        if (list_data != null) {
            list_data.clear()
        }
        if (list_rec != null) {
            list_rec.clear()
        }
        if (list.adapter != null) {
            list.adapter!!.notifyDataSetChanged()
        }

    }

    /**
     * 获取绑定的蓝牙列表
     */
    fun getBondedBlueToothDevices() {
        MainHandler.getInstance().postDelayed({
            clearDataList()
            val device = mBluetoothAdapter.bondedDevices
            if (device.size > 0) {
                if (TextUtils.isEmpty(Sp_net_Util.getInstance().get("blueTooth"))) {
                    judgeIsBindMinde(device.first())
                    Sp_net_Util.getInstance().put("blueTooth", device.first().address)
                }
                device.forEach {
                    list_rec.add(it)
                    judgeIsBindMinde(it)
                }
                list_data.add(Sp_net_Util.getInstance().get("blueTooth"))
                if (list.adapter != null) {
                    list.adapter!!.notifyDataSetChanged()
                }
            }
        },2000)
    }

    fun judgeIsBindMinde(bluetoothDevice:BluetoothDevice){
        if ("CR40_BT".equals(bluetoothDevice.name)){
            Sp_net_Util.getInstance().put("mindeBlueToothDevice",bluetoothDevice.address)
        }
    }
}